﻿using FineUI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZHDJ.Core.Util;
using ZHDJ.Data.Models.JoinParty;
using ZHDJ.Data.Models.Org;
using ZHDJ.JoinParty.BLL;
using ZHDJ.WebPage;

namespace JoinParty.admin.ApplyJoin
{
    public partial class ApplyJoinPartyEdit : PageBase
    {
        private string ApplyIDEX { get; set; }

        /// <summary>
        /// 用于审核者修改用户信息控件
        /// </summary>
        public string Modifly
        {
            get
            {
                return Request.QueryString["Modifly"] ?? string.Empty;
            }
        }
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "";
            }
        }

        private string ppUserValue { get; set; }
        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData(string IsSave = "")
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();

            this.dtBirthday.Text = "1990-01-01";
            if (!string.IsNullOrEmpty(IsSave))
            {
                ApplyIDEX = IsSave;
            }
            else { ApplyIDEX = AppllicationID; }

            PartyJoinProcess process = DB.PartyJoinProcesss.Find(ProcesUtil.JoinStep1);
            this.lbWorkGuide.Text = process.WorkPoint ?? "";

            if (!string.IsNullOrEmpty(ApplyIDEX))
            {
                hdApplyID.Value = ApplyIDEX;
                #region
                PartyJoinApplycation pja = DB.PartyJoinApplycation.Find(hdApplyID.Value);
                PartyOrgMember om = DB.PartyOrgMembers.Find(pja.LoginID);
                this.hdLoginID.Value = pja.LoginID;
                if (pja == null)
                {
                    // 参数错误，首先弹出Alert对话框然后关闭弹出窗口
                    Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
                this.ppUser.Text = ControlBusiness.GetMembersPickerText(om.LoginID);
                this.ppUser.Value = om.LoginID;
                this.ddlGrean.SelectedValue = om.Gender;
                this.txtIDCard.Text = om.IdentityCard;
                if (!string.IsNullOrEmpty(Convert.ToString(om.Birthday)))
                {
                    this.dtBirthday.Text = om.Birthday?.ToString("yyyy-MM-dd");
                }
                this.txtNation.Text = om.Nation;
                this.txtNativePlace.Text = om.NativePlace;
                this.ddlEducation.SelectedValue = om.Educational;
                this.txtMobileNo.Text = om.MobileNo;
                this.txtEmail.Text = om.Email;
                this.txtQQNo.Text = om.QQNumber;
                this.txtWeiXinNo.Text = om.WeiXinNo;
                this.dtApplyTime.Text = Convert.ToDateTime(pja.CreateTime).ToString("yyyy-MM-dd");
                this.ppBranch.Text = ControlBusiness.GetBranchPickerText(om.BranchID);
                this.ppBranch.Value = om.BranchID;
                this.heContent.Text = pja.Content;
                this.txtNature.Text = pja.Nature;
                this.txtBeforeName.Text = pja.BeforeName;

                //工作地址、居住地址、工作单位
                this.txtWorkAddress.Text = om.WorkAddress;
                this.txtAddress.Text = om.Address;
                this.txtWorkUnit.Text = om.WorkUnit;
                this.hdFileId.Text = om.ImageUrl;
                this.imgPhoto.ImageUrl = UpFileBusiness.GetFileUrl(om.ImageUrl);

                if (pja.Status != 0 && pja.Status != 3)
                {
                    this.btnSaveClose.Hidden = true;
                    this.btnSubmit.Hidden = true;
                }
                if (ReadOnly.Equals("1") && IsJoinPartyAdmin)
                {
                    this.btnSaveClose.Hidden = false;
                }
                this.ppUser.Enabled = false;
                #endregion
            }
            else
            {
                if (!string.IsNullOrEmpty(this.CurrentUser.LoginID))
                {
                    if (string.IsNullOrEmpty(this.ppUser.Value))
                    {
                        this.ppUser.Value = this.CurrentUser.LoginID;
                    }
                    PartyOrgMember om = DB.PartyOrgMembers.Where(a => a.LoginID == this.ppUser.Value).FirstOrDefault();

                    this.ppUser.Text = om.UserName;
                    this.ppUser.Value = om.LoginID;
                    this.ddlGrean.SelectedValue = om.Gender;
                    this.txtIDCard.Text = om.IdentityCard;
                    if (!string.IsNullOrEmpty(Convert.ToString(om.Birthday)) && Convert.ToString(om.Birthday?.Year) != "1" && Convert.ToString(om.Birthday?.Year) != "1900")
                    {
                        this.dtBirthday.Text = om.Birthday?.ToString("yyyy-MM-dd");
                    }
                    this.txtNation.Text = om.Nation;
                    this.txtNativePlace.Text = om.NativePlace;
                    this.ddlEducation.SelectedValue = om.Educational;
                    this.txtMobileNo.Text = om.MobileNo;
                    this.txtEmail.Text = om.Email;
                    this.txtQQNo.Text = om.QQNumber;
                    this.txtWeiXinNo.Text = om.WeiXinNo;
                    this.dtApplyTime.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    this.ppBranch.Text = ControlBusiness.GetBranchPickerText(om.BranchID);
                    this.ppBranch.Value = om.BranchID;
                    //工作地址、居住地址、工作单位
                    this.txtWorkAddress.Text = om.WorkAddress;
                    this.txtAddress.Text = om.Address;
                    this.txtWorkUnit.Text = om.WorkUnit;

                    this.dtApplyTime.Text = DateTime.Now.ToString("yyyy-MM-dd");
                }
            }
            SetControlsReadOnly();
            if (Stype)
            {
                this.ppUser.Enabled = false;
            }
        }

        private void SetControlsReadOnly()
        {
            if (this.ReadOnly.Equals("1"))
            {
                this.btnSaveClose.Hidden = true;
                this.heContent.Enabled = false;
                this.btnSubmit.Hidden = true;
                //this.ppUser.Enabled = false;
                this.ddlGrean.Enabled = false;
                this.txtIDCard.Enabled = false;
                this.dtBirthday.Enabled = false;
                this.txtNation.Enabled = false;
                //this.fuFile.Visible = false; 上传控件ID
                this.txtNativePlace.Enabled = false;
                this.ddlEducation.Enabled = false;
                this.txtMobileNo.Enabled = false;
                this.txtEmail.Enabled = false;
                this.txtQQNo.Enabled = false;
                this.txtWeiXinNo.Enabled = false;
                this.txtAddress.Enabled = false;
                this.txtWorkUnit.Enabled = false;
                this.txtWorkAddress.Enabled = false;
                this.dtApplyTime.Enabled = false;
                this.ppBranch.Enabled = false;

            }
            ///用于流程审核者修改申请人信息
            if (this.Modifly == "true")
            {

                this.btnSaveClose.Hidden = true;
                this.heContent.Enabled = false;
                this.btnSubmit.Hidden = true;
                this.ppUser.Enabled = false;
                this.ddlGrean.Enabled = false;
                this.txtIDCard.Enabled = false;
                //this.fuFile.Visible = false;
                this.txtMobileNo.Enabled = false;
                this.txtEmail.Enabled = false;
                this.txtQQNo.Enabled = false;
                this.txtWeiXinNo.Enabled = false;

                this.ppBranch.Enabled = false;

                //保存
                this.btnSaveClose.Hidden = false;
                //出生日期
                this.dtBirthday.Enabled = true;
                //民族
                this.txtNation.Readonly = false;
                //贯籍
                this.txtNativePlace.Readonly = false; ;
                //学历
                this.ddlEducation.Enabled = true;
                //居住地址
                this.txtAddress.Readonly = false;
                //式作所在地
                this.txtWorkAddress.Readonly = false;
                //工作单位
                this.txtWorkUnit.Readonly = false;
                //递交申请书时间
                this.dtApplyTime.Enabled = true;

            }
            //如果是管理员
            if (IsJoinPartyAdmin)
            {
                this.btnSaveClose.Hidden = false;
                this.heContent.Enabled = true;
            }
        }

        private void SaveData(bool isNoStatus = false)
        {
            if (string.IsNullOrEmpty(this.ppUser.Value))
            {
                Alert.Show("人员不能为空。", String.Empty, ActiveWindow.GetHideReference());
                return;
            }
            bool bResult = false;
            //验证身份证与手机号码的唯一性
            if (ModuleUtil.CheckLoginIDCount(txtIDCard.Text.Trim(), this.ppUser.Value) && txtIDCard.Text.Trim() != "")
            {
                Alert.Show(string.Format("你输入的身份证：{0}已经存在，请确认！", txtIDCard.Text.Trim()), String.Empty, ActiveWindow.GetHideReference());
                return;
            }
            if (ModuleUtil.CheckLoginIDCount(txtMobileNo.Text.Trim(), this.ppUser.Value) && txtMobileNo.Text.Trim() != "")
            {
                Alert.Show(string.Format("你输入的手机号码：{0}已经存在，请确认！", txtMobileNo.Text.Trim()), String.Empty, ActiveWindow.GetHideReference());
                return;
            }
            PartyOrgMember om = DB.PartyOrgMembers.Where(a => a.LoginID == this.ppUser.Value).FirstOrDefault();
            if (om == null)
                om = new PartyOrgMember();
            else
                om.ModifyTimeEx = DateTime.Now;
            om.BranchID = this.ppBranch.Value;
            om.Gender = this.ddlGrean.SelectedValue;
            om.IdentityCard = this.txtIDCard.Text.Trim();
            if (!string.IsNullOrEmpty(this.dtBirthday.Text))
            {
                om.Birthday = Convert.ToDateTime(this.dtBirthday.Text);
            }
            if (!string.IsNullOrEmpty(hdFileId.Text))
            {
                om.ImageUrl = hdFileId.Text;
            }
            om.Nation = this.txtNation.Text.Trim();
            om.NativePlace = this.txtNativePlace.Text.Trim();
            //om.ImageUrl = hdFileID.Value;
            om.Educational = this.ddlEducation.SelectedValue;
            om.MobileNo = this.txtMobileNo.Text.Trim();
            om.Email = this.txtEmail.Text.Trim();
            om.QQNumber = this.txtQQNo.Text.Trim();
            om.WeiXinNo = this.txtWeiXinNo.Text.Trim();


            om.Address = this.txtAddress.Text.Trim();
            om.WorkUnit = this.txtWorkUnit.Text.Trim();
            om.WorkAddress = this.txtWorkAddress.Text.Trim();
            DB.SaveChanges();
            PartyJoinApplycation pja = new PartyJoinApplycation();

            if (!string.IsNullOrEmpty(hdApplyID.Value))
            {
                pja = DB.PartyJoinApplycation.Find(hdApplyID.Value);

                pja.BranchID = this.ppBranch.Value;
                pja.CreateTime = Convert.ToDateTime(this.dtApplyTime.Text);
                pja.BeforeName = this.txtBeforeName.Text;
                pja.Nature = this.txtNature.Text;
                DB.SaveChanges();
                if (ReadOnly.Equals("1") && IsJoinPartyAdmin)
                {

                }
                else
                {
                    var link = DB.PartyJoinLinkExamples.Where(a => a.AppllicationID == hdApplyID.Value);
                    if (link != null) { }
                    else
                    {
                        if (!isNoStatus)
                        {
                            if (hdApplyStatus.Value == "0")  //0:表示保存，1：表示提交
                            {
                                pja.Status = (int)Enum_ApplyStatus.草稿;
                            }
                            else
                            {
                                pja.Status = (int)Enum_ApplyStatus.申请中;
                            }
                        }
                    }
                }
                if (!isNoStatus)
                {
                    if (hdApplyStatus.Value == "0")  //0:表示保存，1：表示提交
                    {
                        pja.Status = (int)Enum_ApplyStatus.草稿;
                    }
                    else
                    {
                        pja.Status = (int)Enum_ApplyStatus.申请中;
                    }
                }
                pja.Content = this.heContent.Text;
                bResult = DB.SaveChanges() > 0;
                //if (bResult)
                //{
                //    om.ModifyTimeEx = DateTime.Now;
                //    //更新用户表基本信息
                //    DB.PartyOrgMembers.Add(om);
                //    DB.SaveChanges();
                //}

                //插入流程步骤信息
                if (hdApplyStatus.Value == "1")
                {
                    if (!PartyJoinApplycation.IsApplyOver(hdApplyID.Value))
                    {
                        ProcesUtil.CreateProcesStep(hdApplyID.Value, this.ppBranch.Value, this.ppUser.Value, this.ppUser.Text);
                    }
                    else
                    {
                        Alert.Show("你已经提交了申请，请确认！", String.Empty, ActiveWindow.GetHideReference());
                    }
                }
            }
            else
            {
                pja = new PartyJoinApplycation();
                //申请ID
                pja.AppllicationID = this.hdApplyID.Value = StringHelper.NewID;

                pja.Content = this.heContent.Text;
                pja.BranchID = this.ppBranch.Value;

                om.Address = this.txtAddress.Text.Trim();
                om.WorkUnit = this.txtWorkUnit.Text.Trim();
                om.WorkAddress = this.txtWorkAddress.Text.Trim();

                pja.LoginID = this.ppUser.Value;
                pja.UserName = this.ppUser.Text.Trim();
                pja.CreateTime = Convert.ToDateTime(this.dtApplyTime.Text);
                pja.CreateUserID = this.CurrentUser.LoginID;
                pja.BeforeName = this.txtBeforeName.Text;
                pja.Nature = this.txtNature.Text;
                if (!isNoStatus)
                {
                    if (this.hdApplyStatus.Value == "0")  //0:表示保存，1：表示提交
                    {
                        pja.Status = (int)Enum_ApplyStatus.草稿;
                    }
                    else
                    {
                        pja.Status = (int)Enum_ApplyStatus.申请中;
                    }
                }

                DB.PartyJoinApplycation.Add(pja);
                bResult = DB.SaveChanges() > 0;//添加用户申请信息、更新用户表基本信息                

                //插入流程步骤信息
                if (this.hdApplyStatus.Value == "1")
                {
                    if (!PartyJoinApplycation.IsApplyOver(hdApplyID.Value))
                    {
                        ProcesUtil.CreateProcesStep(hdApplyID.Value, this.ppBranch.Value, this.ppUser.Value, this.ppUser.Text);
                    }
                    else
                    {
                        Alert.Show("你已经提交了申请，请确认！", String.Empty, ActiveWindow.GetHideReference());
                    }
                }
            }
            //if (bResult)
            //{
            //    //switch (this.hdApplyStatus.Value)
            //    //{
            //    //    case "0": Alert.Show("保存成功！", String.Empty, ActiveWindow.GetHideReference()); break;
            //    //    case "1": Alert.Show("提交成功！", String.Empty, ActiveWindow.GetHideReference()); break;
            //    //}
            //}
        }
        #endregion

        #region Events

        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            hdApplyStatus.Value = "0";
            SaveData(true);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            Alert.Show("保存成功！", String.Empty, ActiveWindow.GetHideReference());
        }

        #endregion

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            hdApplyStatus.Value = "1";
            SaveData();
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            Alert.Show("提交成功！", String.Empty, ActiveWindow.GetHideReference());
        }

        protected void ppUser_TextChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void filePhoto_FileSelected(object sender, EventArgs e)
        {
            var rs = UpFileBusiness.Upload(filePhoto, CurrentUser.LoginID, "个人头像");
            if (rs.IsSuccess)
            {
                hdFileId.Text = rs.FileID;
                imgPhoto.ImageUrl = "~/" + rs.FileUrl;
                imgPhoto.ImageWidth = Unit.Pixel(200);

            }
        }
    }
}